package com.alibaba.citrus.ots.platform.enhance.functions.diff.activity.router;

import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.citrus.ots.common.exception.FacadeException;
import com.alibaba.citrus.ots.common.util.SpringContextUtil;
import com.alibaba.citrus.ots.platform.enhance.facade.service.diff.common.DiffCheckRequest;
import com.alibaba.citrus.ots.platform.enhance.functions.diff.activity.constant.ActivityDiffStandardFieldDict;
import com.alibaba.citrus.ots.platform.enhance.functions.diff.common.constant.DiffStrategyRouteDict;
import com.alibaba.citrus.ots.platform.enhance.functions.diff.common.constant.SalesOrderLineDiffStandardFieldDict;
import com.alibaba.citrus.ots.platform.enhance.functions.diff.common.template.OneDiffOneTemplate;
import com.alibaba.citrus.ots.platform.enhance.functions.diff.common.router.DiffCheckProcessor;
import com.alibaba.citrus.ots.platform.enhance.repository.ActivityQueryRepository;
import com.alibaba.citrus.ots.platform.enhance.repository.model.diff.activity.QueryActivityTermParam;
import com.alibaba.citrus.ots.platform.enhance.repository.model.diff.common.FieldLineDTO;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.otspricecenter.sdo.ActivityTermSDO;
import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.IExpressContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

/**
 * @author: qiaojiange
 * @create: 2022/01/19
 * @Description 活动使用记录（基准）和 销售子单 之间的对账
 */
@Component
public class SalesOrderLineDiffActivityUseRecordProcessor extends DiffCheckProcessor {

    private Log log = Log.getLogger(SalesOrderLineDiffActivityUseRecordProcessor.class);

    /**
     * 规则表达式引擎
     */
    @Resource
    private  ExpressRunner expressRunner ;

    @Resource
    private OneDiffOneTemplate oneDiffOneTemplate;

    @Resource
    private ActivityQueryRepository activityQueryRepository;

    @Override
    public String obtainStrategyRoute() {
        return DiffStrategyRouteDict.SALES_ORDER_LINE_DIFF_ACTIVITY.getStrategyCode();
    }

    @Override
    @ProcessInvoker
    public Result<String> diff(DiffCheckRequest diffCheckRequest) {
        //这里单独的使用每一个字段进行对账
        Map<String, FieldLineDTO> baseLineDataMap = diffCheckRequest.getBaseLineDataMap();
        Map<String, FieldLineDTO> activityUseRelationDiffDataMap = diffCheckRequest.getDiffDataMap();

        IExpressContext<String, Object> context = new DefaultContext<>();
        for (Map.Entry<String, FieldLineDTO> entry : baseLineDataMap.entrySet()) {
            context.put(entry.getKey(), entry.getValue().getFieldValue());
        }

        context.put("unitPrice",Integer.parseInt((String) context.get("unitPrice")));
        context.put("specialOfferPrice",Integer.parseInt((String) context.get("specialOfferPrice")));
        context.put("itemQuantity",Integer.parseInt((String) context.get("itemQuantity")));

        String rule = "itemQuantity*(unitPrice-specialOfferPrice)";
        String activityOccupyFee = null;
        try {
            activityOccupyFee = "" + expressRunner.execute(rule, context, null, true, false);
        } catch (Exception e) {
            log.error("表达式计算错误", e);
            throw new FacadeException("OTS-13-002-01-16-001");
        }

        FieldLineDTO fieldLineDTO = FieldLineDTO.of("", ActivityDiffStandardFieldDict.ACTIVITY_OCCUPY_FEE.getFieldCode(), activityOccupyFee);
        baseLineDataMap.put(ActivityDiffStandardFieldDict.ACTIVITY_OCCUPY_FEE.getFieldCode(), fieldLineDTO);


        //活动使用状态处理，根据销售子单拒绝原因设置状态
        FieldLineDTO refuseReasonDTO = baseLineDataMap.get(SalesOrderLineDiffStandardFieldDict.REFUSE_REASON_CODE.getFieldCode());
        FieldLineDTO activityUseStatusDTO = null;
        if (StringUtils.isNotBlank(refuseReasonDTO.getFieldValue())) {
            activityUseStatusDTO = FieldLineDTO.of("", ActivityDiffStandardFieldDict.ACTIVITY_USE_RECORD_STATUS.getFieldCode(), "-1");
        } else {
            activityUseStatusDTO = FieldLineDTO.of("", ActivityDiffStandardFieldDict.ACTIVITY_USE_RECORD_STATUS.getFieldCode(), "1");
        }
        baseLineDataMap.put(ActivityDiffStandardFieldDict.ACTIVITY_USE_RECORD_STATUS.getFieldCode(), activityUseStatusDTO);



        //目前通过查询活动项目表获取活动价，实际上特价有普通特价和坎级特价的两种情况，分别存在活动项目表和坎级活动表里面，这里先这样取值 ...todo hanguo
        FieldLineDTO activityIdDTO = activityUseRelationDiffDataMap.get(ActivityDiffStandardFieldDict.ACTIVITY_ID.getFieldCode());
        FieldLineDTO activityTermIdDTO = activityUseRelationDiffDataMap.get(ActivityDiffStandardFieldDict.ACTIVITY_TERM_ID.getFieldCode());
        String activityId = activityIdDTO.getFieldValue();
        String activityTermId = activityTermIdDTO.getFieldValue();
        if (StringUtils.isNotBlank(activityId) && StringUtils.isNotBlank(activityTermId)) {
            QueryActivityTermParam queryActivityTermParam = new QueryActivityTermParam();
            queryActivityTermParam.setActivityId(activityId);
            queryActivityTermParam.setActivityTermId(activityTermId);
            Result<ActivityTermSDO> activityTermSDOResult = activityQueryRepository.queryActivityTerm(queryActivityTermParam);
            if (Objects.nonNull(activityTermSDOResult) && Objects.nonNull(activityTermSDOResult.getResult())) {
                FieldLineDTO specialPriceDTO = FieldLineDTO.of("", SalesOrderLineDiffStandardFieldDict.SPECIAL_OFFER_PRICE.getFieldCode()
                        , activityTermSDOResult.getResult().getSpecialOfferPrice());
                activityUseRelationDiffDataMap.put(SalesOrderLineDiffStandardFieldDict.SPECIAL_OFFER_PRICE.getFieldCode(), specialPriceDTO);
            }
        }

        return super.diff(diffCheckRequest, oneDiffOneTemplate);
    }
}
